package com.buddha.api.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.buddha.api.common.Result;
import com.buddha.api.dto.ClientDto;
import com.buddha.api.entity.Article;
import com.buddha.api.entity.Car;
import com.buddha.api.entity.User;
import com.buddha.api.service.impl.ArticleServiceImpl;
import com.buddha.api.service.impl.CarServiceImpl;
import com.buddha.api.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author mybatis-plus
 * @since 2023-07-06
 */
@CrossOrigin(origins = {"*"})
@RestController
@RequestMapping("/article")
public class ArticleController {

    @Autowired
    private ArticleServiceImpl articleService;
    @Autowired
    private UserServiceImpl userService;

    @Autowired
    private CarServiceImpl carService;

    @PostMapping()
    public Result saveClient(@RequestBody Article article){
        article.setIssueTime(LocalDateTime.now());
        return Result.success(articleService.saveOrUpdate(article));
    }


    @Transactional
    @PostMapping("/delete")
    public Result delete(@RequestBody Integer[] ids) {
        for (Integer id : ids) {
            articleService.removeById(id);
        }
        return Result.success();
    }

    @GetMapping
    public Result findAll() {
        List<Article> list = articleService.findAllNotPass();
        return Result.success(list);
    }

    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        Article article = articleService.getById(id);
        ClientDto dto = new ClientDto();
        User client = userService.getById(article.getClientId());
        dto.setId(client.getId());
        dto.setUsername(client.getUsername());
        dto.setAvatar(client.getAvatar());
        article.setClient(dto);
        return Result.success(article);
    }

    @GetMapping("/page")
    public Result findPage(
            @RequestParam(defaultValue = "") String context,
            @RequestParam Integer pageNum,
            @RequestParam Integer pageSize) {
        QueryWrapper<Article> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("context",context);
        queryWrapper.ne("state",1);
        queryWrapper.orderByDesc("commit_time");
        Page<Article> page = articleService.page(new Page<>(pageNum, pageSize), queryWrapper);
        System.out.println();
        for (Article record : page.getRecords()) {
            User client = userService.getById(record.getClientId());
            ClientDto dto = new ClientDto();
            dto.setId(client.getId());
            dto.setUsername(client.getUsername());
            dto.setAvatar(client.getAvatar());
            record.setClient(dto);
        }
        return Result.success(page);
    }

    @GetMapping("/page1")
    public Result findPage1(
            @RequestParam(defaultValue = "") String context,
            @RequestParam Integer pageNum,
            @RequestParam Integer pageSize) {
        QueryWrapper<Article> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("context",context);
        Page<Article> page = articleService.page(new Page<>(pageNum, pageSize), queryWrapper);
/*        for (Article record : page.getRecords()) {
            User client = userService.getById(record.getClientId());
            ClientDto dto = new ClientDto();
            dto.setId(client.getId());
            dto.setUsername(client.getUsername());
            dto.setAvatar(client.getAvatar());
            record.setClient(dto);
            Car car = carService.getById(record.getCarId());
            record.setBrandId(car.getBrandId());
        }*/
        return Result.success(page);
    }


    @PostMapping("/save")
    public Result saveBlog(@RequestBody Article article, HttpServletRequest request, Principal principal){
        String userName = principal.getName();
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username",userName);
        User user = userService.getOne(wrapper);
        article.setClientId(user.getId());
        article.setCommitTime(LocalDateTime.now());
        if (article.getState() == null){
            article.setState(0);
        }
        //System.out.println("userName:"+userName);
        boolean flag;
        if(article.getId() == null){
            flag = articleService.save(article);
            return flag?Result.success():Result.error("300","添加失败");
        }else{
            articleService.updateById(article);
            return Result.success();
        }
    }

    @GetMapping("/get")
    public Result GetBlog(@RequestParam Integer articleId){
        Article article = articleService.getById(articleId);
        return Result.success(article);
    }

    @GetMapping("/car/id")
    public Result getCarById(@RequestParam Integer carId){
        QueryWrapper<Article> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("car_id",carId);
        queryWrapper.last("LIMIT 3");
        List<Article> articles = articleService.list(queryWrapper);
        return Result.success(articles);
    }

    @GetMapping("/my")
    Result GetMyArticle(@RequestParam Integer pageNum,
                        @RequestParam Integer pageSize,
                        Principal principal){
        String userName = principal.getName();
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username",userName);
        User user = userService.getOne(wrapper);

        // 找到用户的文章列表
        QueryWrapper<Article> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("client_id",user.getId());
        Page<Article> page = articleService.page(new Page<>(pageNum, pageSize), queryWrapper);
        return Result.success(page);
    }

}
